

package com.zdsx.modules.oss.cloud;

import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.zdsx.common.exception.ErrorCode;
import com.zdsx.common.exception.CommonException;
import com.zdsx.common.utils.DateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

/**
 * 腾讯云存储
 *
 * @author Lr
 */
public class QcloudCloudStorageService extends AbstractCloudStorageService {
    private COSCredentials credentials;
    private ClientConfig clientConfig;

    public QcloudCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        //1、初始化用户身份信息(secretId, secretKey)
        credentials = new BasicCOSCredentials(config.getQcloudSecretId(), config.getQcloudSecretKey());
    	
    	//2、设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        clientConfig = new ClientConfig(new Region(config.getQcloudRegion()));
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
    	try {
            COSClient client = new COSClient(credentials, clientConfig);

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            String bucketName = config.getQcloudBucketName() +"-"+ config.getQcloudAppId();
            PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream, metadata);
            PutObjectResult result = client.putObject(request);

            client.shutdown();
            if(result.getETag() == null){
                throw new CommonException(ErrorCode.OSS_UPLOAD_FILE_ERROR, "");
            }
        } catch (IOException e) {
            throw new CommonException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

        return config.getQcloudDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getQcloudPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getQcloudPrefix(), suffix));
    }

    @Override
    public String generatePresignedUrl(String fileName, HttpMethodName httpMethodName) {

        try {
            COSClient client = new COSClient(credentials, clientConfig);
            String bucketName = config.getQcloudBucketName();// + "-" + config.getQcloudAppId();

            String key = String.format("images/%s", fileName);
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, httpMethodName);

            if (httpMethodName == HttpMethodName.GET) {
                Calendar calendar = Calendar.getInstance();
                // 将100年添加到当前时间
                calendar.add(Calendar.YEAR, 100);
                request.setExpiration(calendar.getTime());
            }

            // 该字段为非必填，主要是用来限制文件上传类型，用户不填即不开启
//            if (StrUtil.isNotBlank(bo.getContentType())) {
//                request.setContentType(bo.getContentType());
//            }

            // 该字段为非必填，用来校验文件完整性，用户不填即不开启
//            if (StringUtils.isNotBlank(bo.getContentMd5())) {
//                request.setContentMd5(bo.getContentMd5());
//            }

            URL url = client.generatePresignedUrl(request);

            // 保存图片key

            return url.toString();

        } catch (Exception e) {
            throw new CommonException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }

    }

    @Override
    public String getObjectUrl(String fileName) {
        try {
            COSClient client = new COSClient(credentials, clientConfig);
            String bucketName = config.getQcloudBucketName();// + "-" + config.getQcloudAppId();

            String key = String.format("images/%s", fileName);
//            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
//            request.setMethod(HttpMethodName.PUT);

            // 该字段为非必填，主要是用来限制文件上传类型，用户不填即不开启
//            if (StrUtil.isNotBlank(bo.getContentType())) {
//                request.setContentType(bo.getContentType());
//            }

            // 该字段为非必填，用来校验文件完整性，用户不填即不开启
//            if (StringUtils.isNotBlank(bo.getContentMd5())) {
//                request.setContentMd5(bo.getContentMd5());
//            }

//            URL url = client.generatePresignedUrl(request);

            // 保存图片key

            URL url = client.getObjectUrl(bucketName, key);

            return url.toString();

        } catch (Exception e) {
            throw new CommonException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
    }
}